package postgres

import (
	log "aggregation/collector/logger"
	"aggregation/config"
	"context"
	"database/sql"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

var dbAuth *gorm.DB
var dbManger *gorm.DB

const AUTHCONTEXTKEY = "AUTH"
const MANAGERCONTEXTKEY = "MANAGER"

func GetAuthDB(ctx context.Context) *gorm.DB {
	tx, ok := ctx.Value(AUTHCONTEXTKEY).(*gorm.DB)
	if ok {
		return tx
	}
	return dbAuth.WithContext(ctx)
}

func GetManagerDB(ctx context.Context) *gorm.DB {
	tx, ok := ctx.Value(MANAGERCONTEXTKEY).(*gorm.DB)
	if ok {
		return tx
	}
	return dbManger.WithContext(ctx)
}

func Init(connectAddr string, dbName string) func() {
	var (
		err   error
		sqlDB *sql.DB
	)
	switch dbName {
	case "auth":
		if dbAuth, err = gorm.Open(postgres.Open(connectAddr), &gorm.Config{}); err != nil {
			log.Fatal(err)
		}
		if sqlDB, err = dbAuth.DB(); err != nil {
			log.Fatal(err)
		}
		sqlDB.SetMaxIdleConns(50)
		sqlDB.SetMaxOpenConns(500)

		if err = sqlDB.Ping(); err != nil {
			panic(err)
		}

		if config.Conf.Env == "dev" {
			dbAuth = dbAuth.Debug()
		}
	case "manager":
		if dbManger, err = gorm.Open(postgres.Open(connectAddr), &gorm.Config{}); err != nil {
			log.Fatal(err)
		}
		if sqlDB, err = dbManger.DB(); err != nil {
			log.Fatal(err)
		}
		sqlDB.SetMaxIdleConns(50)
		sqlDB.SetMaxOpenConns(500)

		if err = sqlDB.Ping(); err != nil {
			panic(err)
		}

		if config.Conf.Env == "dev" {
			dbManger = dbManger.Debug()
		}

	}
	return func() {
		if err = sqlDB.Close(); err != nil {
			log.Error(err)
		}
	}
}
